package com.sim.server.command.handler;

import com.sim.core.*;
import com.sim.core.exception.ImException;
import com.sim.server.SimServerAPI;
import com.sim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sim.core.packets.Command;
import com.sim.core.packets.ExitGroupNotifyRespBody;
import com.sim.core.packets.OutGroupReqBody;
import com.sim.core.packets.RespBody;
import com.sim.core.packets.User;
import com.sim.core.utils.JsonKit;
import com.sim.server.command.AbstractCmdHandler;

/**
 *
 * 版本: [1.0]
 * 功能说明: 加入群组消息cmd命令处理器
 * @author : God 创建时间: 2017年9月21日 下午3:33:23
 */
public class OutGroupReqHandler extends AbstractCmdHandler {

    private static Logger log = LoggerFactory.getLogger(OutGroupReqHandler.class);

    @Override
    public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {
        OutGroupReqBody outGroupReqBody = JsonKit.toBean(packet.getBody(), OutGroupReqBody.class);
        String groupId = outGroupReqBody.getGroupId();
        //发退出房间通知  COMMAND_EXIT_GROUP_NOTIFY_RESP
        ExitGroupNotifyRespBody exitGroupNotifyRespBody = new ExitGroupNotifyRespBody();
        exitGroupNotifyRespBody.setGroup(groupId);
        User clientUser = channelContext.getSessionContext().getImClientNode().getUser();
        if(clientUser != null) {
            User notifyUser = User.newBuilder().userId(clientUser.getUserId()).nick(clientUser.getNick()).build();
            exitGroupNotifyRespBody.setUser(notifyUser);
            RespBody respBody = new RespBody(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP,exitGroupNotifyRespBody);
            ImPacket imPacket = new ImPacket(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP, respBody.toByte());
            SimServerAPI.sendToGroup(outGroupReqBody.getGroupId(), imPacket);
        }
        RespBody respBody = null;
        if (SimServerAPI.unbindGroup(groupId, channelContext)) {
            respBody = new RespBody(Command.COMMAND_OUT_GROUP_RESP,ImStatus.C10023).setData(outGroupReqBody);
        }else {
            respBody = new RespBody(Command.COMMAND_OUT_GROUP_RESP,ImStatus.C10024).setData(outGroupReqBody);
        }
        return ProtocolManager.Converter.respPacket(respBody, channelContext);

    }

    @Override
    public Command command() {
        return Command.COMMAND_OUT_GROUP_REQ;
    }
}
